import { Button, Card, notification, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import menuService from '@/api/services/security/menuService';
import permissionService from '@/api/services/security/permissionService';
import { IconButton, Iconify } from '@/components/icon';
// eslint-disable-next-line import/named
import PermissionFilterForm, {
  PermissionSearchForm,
} from '@/pages/management/system/permission/permission-search-form';
import ProTag from '@/theme/antd/components/tag';
import { pagination } from '@/utils/pagination';
import { hasPermission } from '@/utils/permission';

import PermissionModal, { type PermissionModalProps } from './permission-modal';

import { ListData, Permission } from '#/entity';

const defaultPermissionValue: Permission = {
  name: '',
  isImmutable: false,
  rules: [],
};
export default function PermissionPage() {
  const [searchForm, setSearchForm] = useState<PermissionSearchForm>({
    page: 1,
    take: 10,
  });
  const [tableData, setTableData] = useState<ListData<Permission>>();
  const [permissionModalProps, setPermissionModalProps] = useState<PermissionModalProps>({
    formValue: { ...defaultPermissionValue },
    title: '创建权限',
    show: false,
    onOk: () => {
      setPermissionModalProps((prev) => ({ ...prev, show: false }));
      setSearchForm({ page: 1, take: 10 });
    },
    onCancel: () => {
      setPermissionModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  useEffect(() => {
    permissionService.PermissionList(searchForm).then((data) => {
      setTableData(data);
    });
  }, [searchForm]);
  const columns: ColumnsType<Permission> = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
    },
    {
      title: '模块',
      dataIndex: 'module',
      width: 60,
      render: (_, record) => <ProTag color="processing">{record.module?.name}</ProTag>,
    },
    {
      title: '是否只读',
      dataIndex: 'immutable',
      width: 60,
      render: (isImmutable: boolean) => {
        if (isImmutable) {
          return <ProTag color="processing">是</ProTag>;
        }
        return <ProTag color="processing">否</ProTag>;
      },
    },
    {
      fixed: 'right' as const,
      align: 'right' as const,
      title: <div style={{ marginRight: 20 }}>操作</div>,
      width: 100,
      render: (_: any, record) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('SECURITY:PERMISSION:UPDATE') && hasPermission('SECURITY:MENU:READ') && (
            <IconButton onClick={() => onEdit(record)}>
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </IconButton>
          )}
          {hasPermission('SECURITY:PERMISSION:DELETE') && (
            <Popconfirm
              title="确定删除该权限，删除后关联的数据会一并删除?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => onDelete(record)}
              placement="left"
            >
              <IconButton>
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </IconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  const onCreate = (parentId?: string) => {
    setPermissionModalProps((prev) => ({
      ...prev,
      show: true,
      ...defaultPermissionValue,
      title: '创建权限',
      formValue: { ...defaultPermissionValue, parentId: parentId ?? '' },
    }));
  };

  const onEdit = (formValue: Permission) => {
    menuService.flattenMenuList({ permissionId: formValue.id! }).then((res) => {
      formValue.rules = res;
      setPermissionModalProps((prev) => ({
        ...prev,
        show: true,
        title: '修改权限',
        formValue,
      }));
    });
  };

  const onDelete = (item: Permission) => {
    permissionService.deletePermission(item.id!).then((res) => {
      if (res > 0) {
        notification.success({ message: '删除成功' });
        setSearchForm({ page: 1, take: 10 });
      } else {
        notification.error({ message: '删除失败，请联系管理员' });
      }
    });
  };
  const onFinish = (values: any) => {
    setSearchForm((prev) => ({
      ...prev,
      text: values.text,
    }));
  };
  const reset = () => {
    onFinish([]);
  };
  return (
    <>
      <PermissionFilterForm onOk={onFinish} onReset={reset} />
      <br />
      <Card
        title="权限列表"
        extra={
          hasPermission('SECURITY:PERMISSION:CREATE') &&
          hasPermission('SECURITY:MENU:READ') && (
            <Button type="primary" onClick={() => onCreate()}>
              创建
            </Button>
          )
        }
      >
        <Table
          rowKey="id"
          size="small"
          scroll={{ x: 'max-content' }}
          pagination={pagination({
            page: searchForm,
            onPageChange: (page, rows) => {
              setSearchForm((prev) => ({
                ...prev,
                page,
                take: rows,
              }));
            },
            count: tableData?.count,
          })}
          columns={columns}
          dataSource={tableData?.data}
        />
        {hasPermission('SECURITY:PERMISSION:UPDATE') && hasPermission('SECURITY:MENU:READ') && (
          <PermissionModal {...permissionModalProps} />
        )}
      </Card>
    </>
  );
}
